package com.kaiwukj.android.ufamily.mvp.ui.page.mine;

import android.os.Bundle;
import android.widget.TextView;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.alipay.sdk.app.PayTask;
import com.blankj.utilcode.util.GsonUtils;
import com.blankj.utilcode.util.LogUtils;
import com.kaiwukj.android.ufamily.R;
import com.kaiwukj.android.ufamily.app.base.review.BaseActivity;
import com.kaiwukj.android.ufamily.app.constant.ARouterUrlKt;
import com.kaiwukj.android.ufamily.app.constant.Constant;
import com.kaiwukj.android.ufamily.mvp.helper.TokenStore;
import com.kaiwukj.android.ufamily.mvp.http.entity.event.PayEvent;
import com.kaiwukj.android.ufamily.mvp.http.entity.event.PayInfo;
import com.kaiwukj.android.ufamily.mvp.http.entity.event.PayResult;
import com.kaiwukj.android.ufamily.mvp.http.entity.event.UpdateUserInfoEvent;
import com.kaiwukj.android.ufamily.mvp.http.entity.resultbak.AlipayResult;
import com.kaiwukj.android.ufamily.mvp.ui.widget.home.ShopWebView;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.Observable;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;

@Route(path = ARouterUrlKt.MyVipService)
public class VipWebActivity extends BaseActivity {

    @BindView(R.id.tv_title)
    TextView tvTitle;
    @BindView(R.id.web)
    ShopWebView webView;


    @OnClick(R.id.container_left)
    void onBackClick() {
        onBackPressedSupport();
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_vip_web;
    }

    @Override
    protected void initView(Bundle savedInstanceState) {

        tvTitle.setText("开通会员");

        String token = "";
        /*try {
            token = URLEncoder.encode(TokenStore.getToken(), "utf-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }*/

        String url = String.format("http://vippaytest.jiayuanli.net/?auth=%s", TokenStore.getToken());

        LogUtils.d("url--------------------->" + url);

        webView.loadUrl(url);

        // LogUtils.d("token-------------------->" + token);

        webView.setOnVipServiceListener(new ShopWebView.onVipServiceListener() {
            @Override
            public void onTokenInvalid() {

            }

            @Override
            public void onWXPay(String json) {
                payByWeChat(json);
            }

            @Override
            public void onAlipay(String json) {
                payAli(json);
            }

            @Override
            public void onGoHome() {
                runOnUiThread(() -> finish());
            }
        });

    }


    @Override
    protected void initData(Bundle savedInstanceState) {

    }

    private void payAli(String params) {
        AlipayResult payObj = GsonUtils.fromJson(params, AlipayResult.class);
        subscribe(Observable.create((ObservableOnSubscribe<PayResult>) emitter -> {
            PayTask payTask = new PayTask(this);
            Map<String, String> map = payTask.payV2(payObj.getSign(), true);
            emitter.onNext(new PayResult(map));
        }).subscribeOn(Schedulers.newThread())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(payResult -> {
                    if ("9000".equals(payResult.getResultStatus())) {
                        //EventBus.getDefault().post(new PayEvent(true, 0, "支付成功"));
                        EventBus.getDefault().post(new UpdateUserInfoEvent());
                        webView.setPayStatus(ShopWebView.PAY_OK);
                    } else if ("6001".equals(payResult.getResultStatus())) {
                        //cancelOrder(new PayFeeCancelRequest(result.getTradeNo()));
                        webView.setPayStatus(ShopWebView.PAY_CANCEL);
                    } else {
                        //EventBus.getDefault().post(new PayEvent(false, 0, "支付失败"));
                        webView.setPayStatus(ShopWebView.PAY_FAILED);
                    }
                }));
    }

    private void payByWeChat(String params) {
        PayInfo payInfo = GsonUtils.fromJson(params, PayInfo.class);
        final IWXAPI msgApi = WXAPIFactory.createWXAPI(this, null);
        msgApi.registerApp(Constant.WX_APP_ID);
        if (!msgApi.isWXAppInstalled()) {
            showMessage(getString(R.string.please_install_wechat));
            return;
        }
        msgApi.sendReq(payInfo.getPayReq());
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onPayEvent(PayEvent payEvent) {

        if (payEvent.isSuccess()) {
            //showMessage("支付成功哈");
            EventBus.getDefault().post(new UpdateUserInfoEvent());
            webView.setPayStatus(ShopWebView.PAY_OK);
        } else if (payEvent.getDesc().equals("支付已取消")) {
            webView.setPayStatus(ShopWebView.PAY_CANCEL);
        } else {
            webView.setPayStatus(ShopWebView.PAY_FAILED);
            showMessage(payEvent.getDesc());
        }
    }

}
